package com.siyougame.app.interceptor;


import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;

/**
 * 名称：LogInterceptor <br>
 * 描述：日志拦截器<br>
 * 参考 https://zhuanlan.zhihu.com/p/92159923
 *
 * @author admin
 * @version 1.0
 * @since 1.0.0
 */
@Component
@EnableAutoConfiguration
public class LogInterceptor implements HandlerInterceptor {
    //@Autowired
    //private RedisUtils redisUtils;

    private static final Logger log = LoggerFactory.getLogger("API_ACCESS_LOG");


    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
     * preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("REQUEST_START_TIME", new Date());

        String requestId = IdUtil.simpleUUID();
        String startTime = Long.toString(System.currentTimeMillis());
        String uri = request.getRequestURI();
        String params = request.getParameterMap().entrySet().stream()
                .map(e -> Arrays.stream(e.getValue()).map(v -> e.getKey() + "=" + v)
                        .reduce((v1, v2) -> v1 + "&" + v2).orElse("")
                )
                .reduce((p1, p2) -> p1 + "&" + p2)
                .orElse("");
        String method = request.getMethod();
        String ip = StringUtils.isEmpty(request.getHeader("X-FORWARDED-FOR")) ? request.getLocalAddr() : request.getHeader("X-FORWARDED-FOR");
        String userAgent = request.getHeader("user-agent");
        log.info("request start: requestId: {}, startTime:{}, uri: {}, params: {}, method: {}, ip: {}, user-agent: {}", requestId, startTime, uri, params, method, ip, userAgent);
        MDC.put("requestId", requestId);
        MDC.put("startTime", startTime);
        MDC.put("uri", uri);
        MDC.put("params", params);
        MDC.put("method", method);
        MDC.put("ip", ip);
        MDC.put("userAgent", userAgent);
        return true;

    }

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
     * postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
     * afterCompletion(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler,
                                Exception ex)
            throws Exception {


//        log.info("本次请求耗时：" + (end.getTime() - start.getTime()) + "毫秒；" + getRequestInfo(request).toString());
        //log.info("本次请求耗时：" + (end.getTime() - start.getTime()));
        String endTime = Long.toString(System.currentTimeMillis());
        log.info("request end: requestId: {}, endTime:{}, result: {}", MDC.get("requestId"), endTime, MDC.get("result"));


        MDC.clear();
    }


    /**
     * 主要功能:获取请求详细信息
     * 注意事项:无
     *
     * @param request 请求
     * @return 请求信息
     */
    /*private StringBuilder getRequestInfo(HttpServletRequest request) {
        StringBuilder reqInfo = new StringBuilder();
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        String urlPath = urlPathHelper.getLookupPathForRequest(request);
        reqInfo.append(" 请求路径=" + urlPath);
        reqInfo.append(" 来源IP=" + RequestUtil.getIpAddrByRequest(request));


        String userName = "";
        try {

            SysUserEntity sysUser = (SysUserEntity) SecurityUtils.getSubject().getSession().getAttribute(Global.CURRENT_USER);
            if (sysUser != null) {
                userName = (sysUser.getUsername());
            }

        } catch (Exception e) {

        }
        reqInfo.append(" 操作人=" + (userName));
        reqInfo.append(" 请求参数=" + RequestUtil.getParameters(request).toString());
        return reqInfo;
    }*/
}
